package com.codemobiles.droidslator.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.codemobiles.droidslator.R;
import com.sun.swing.internal.plaf.synth.resources.synth;

public class SettingActivity extends Activity {
	private ImageView imgBanner;
	private ImageView backBtn;
	private ProgressBar mProgress;
	private TextView progressText;
	private Button btnDowload001;
	private int mProgressStatus = 0;

	private boolean isDownloading = false;
	private float fileSeg = 0;
	private int percent = 0;
	private String urlStr = "";
	private final String filePath = ".dsdb";
	private URL fetchUrl;
	private byte[] buff = new byte[1024];
	private int len;
	private int fileSize;
	private InputStream in;
	private FileOutputStream out;
	private File root;

	private Handler mHandler = new Handler();

	@Override
	protected void onPause() {
		super.onPause();
		releaseAllResources();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		releaseAllResources();
	}

	private void releaseAllResources() {
		if (percent != 100 && downloadThread != null){
			deleteFile();
		}
		isCanceled = true;
		downloadThread = null;
		fileSeg = 0;
		fileSize = 0;
		Log.i("POS_LOG", "All resources are released");
	}
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.setting);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.custom_title);

		btnDowload001 = (Button) findViewById(R.id.download001);
		progressText = (TextView) findViewById(R.id.progressText);
		mProgress = (ProgressBar) findViewById(R.id.progress_bar);
		imgBanner = (ImageView) findViewById(R.id.imgBanner);
		backBtn = (ImageView) findViewById(R.id.imgBack);
		initPlugInStatus();

		btnDowload001.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (downloadThread != null) { // when press cancel
					btnDowload001.setText("Install");
					releaseAllResources();
				} else { // when press install
					isCanceled = false;
					fileSeg = 0;
					fileSize = 0;
					percent = 0;
					isCanceled = false;
					isDownloading = false;
					mProgress.setProgress(0);
					btnDowload001.setText("Cancel");
					beginDownload();
				}
			}
		});

		imgBanner.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Uri uri = Uri.parse(getString(R.string.our_website));
				startActivity(new Intent(Intent.ACTION_VIEW, uri));
			}
		});

		backBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		backBtn.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				int eventaction = event.getAction();

				switch (eventaction) {

				case MotionEvent.ACTION_DOWN:
					backBtn.setImageResource(R.drawable.button_back_touch);
					break;

				case MotionEvent.ACTION_MOVE:
					break;

				case MotionEvent.ACTION_UP:
					backBtn.setImageResource(R.drawable.button_back);
					break;
				}

				return false;
			}
		});
	}

	private void initPlugInStatus() {
		root = Environment.getExternalStorageDirectory();
		File file = new File(root, File.separator + filePath);
		try {
			new FileInputStream(file);
			mProgress.setProgress(100);
			btnDowload001.setText("Re-Install");
			progressText.setText("Installed");
		} catch (FileNotFoundException e) {
			btnDowload001.setText("Install");
			progressText.setText("0%");
		}
	}

	private void deleteFile() {
		root = Environment.getExternalStorageDirectory();
		File file = new File(root, File.separator + filePath);
		file.delete();
	}

	private Thread downloadThread;
	private boolean isCanceled = false;

	private void beginDownload() {
		mProgressStatus = 0;
		downloadThread = new Thread(new Runnable() {
			public void run() {
				while (percent < 100
						&& Thread.currentThread() == downloadThread) {
					percent = runDownload();
					// Update the progress bar
					mHandler.post(new Runnable() {
						public void run() {
							mProgress.setProgress(percent);
							if ((percent != 100)) {
								if (isCanceled == false) {
									progressText.setText(percent + "%" + " ("
											+ mProgressStatus + "/" + fileSize
											/ 1024 + " KB)");
								} else {
									mProgress.setProgress(0);
									progressText.setText("0%");
									isCanceled = true;
								}

							} else {
								btnDowload001.setText("Re-Install");
								progressText.setText("Installed");

							}
						}
					});
				}
			}
		});
		downloadThread.start();
	}

	private synchronized int runDownload() {

		try {
			if (isDownloading != true) {
				isDownloading = true;
				urlStr = getString(R.string.urlStr);
				fetchUrl = new URL(urlStr);
				fileSize = fetchUrl.openConnection().getContentLength();
				fileSeg = fileSize / buff.length;
				Log.i("POS_LOG", "file's size: " + String.valueOf(fileSize));
				in = (InputStream) fetchUrl.getContent();
				out = new FileOutputStream(new File(root, File.separator
						+ filePath));
			}

			len = in.read(buff);
			out.write(buff, 0, len);
			mProgressStatus++;
			percent = (int) (((float) (mProgressStatus) / (float) (fileSeg)) * (float) (100));
			if (percent == 100) {
				in.close();
				out.close();
			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			Log.i("POS_TAG", "fromEditor = " + e.getMessage());
			System.out.println(e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.i("POS_TAG", "fromEditor = " + e.getMessage());
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
		return percent;
	}

}
